import { useStore } from '@/hooks';
import { Button, Dialog, Form, Message } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;

const DataForm = ({ onCancel, modal, onSubmit, ...formProps }) => {
  const { driverGroupStore: store } = useStore();
  const { show, record } = modal;
  const [clone] = useState(() => observable({}));
  const [groups, setGroups] = useState(null);
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => {
    if (show === 'clone') {
      (async () => {
        const res = await store.get({ search: {}, pg: { size: 999, page: 0, sort: ['crDate;DESC'] } });
        const tempFilter = res.filter((item) => item.id !== record?.id);
        setGroups(tempFilter);
      })();
    }
    return () => {
      _.set(clone, 'groupId', null);
    };
  }, [show]);

  const handleOnchange = (values, item) => {
    const { name, value } = item;
    _.set(clone, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    const { groupId } = toJS(clone);
    if (!groupId) {
      Message.error({ content: t`请选择群` });
      return;
    }
    Dialog.confirm({
      content: t`确定克隆？`,
      onOk: async () => {
        const findGroup = groups.find((p) => p.id === groupId);
        const {
          priceRules,
          urgentOrderRule,
          takeOrderInterval,
          urgentOrderInterval,
          reserveOrderInterval,
          minimumPoints,
        } = findGroup;
        onSubmit?.({
          ...record,
          priceRules,
          urgentOrderRule,
          takeOrderInterval,
          urgentOrderInterval,
          reserveOrderInterval,
          minimumPoints,
        });
      },
    });
  };

  const handleCancel = () => {
    onCancel?.();
  };

  return (
    <Dialog
      visible={modal.show === 'clone'}
      onClose={handleCancel}
      title={t`克隆规则`}
      style={{ width: '26%' }}
      footer={null}
    >
      <Form {...formProps} value={clone} onChange={handleOnchange} inline useLabelForErrorMessage>
        <FromItem
          label={t`选择群`}
          name="groupId"
          required
          requiredFlag
          errorMessage={t`请选择群`}
          style={{ width: '100%' }}
        >
          <TauSimpleSelect
            dataSource={groups?.map((p) => ({ label: p.groupName, value: p.id }))}
            style={{ width: 260 }}
          />
        </FromItem>
        <DrawerFooter>
          <FromItem>
            <Form.Submit type="primary" onClick={handleSubmit}>{t`确定`}</Form.Submit>
            <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          </FromItem>
        </DrawerFooter>
      </Form>
    </Dialog>
  );
};

export default observer(DataForm);
